﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DTO;
using AutoMapper;

namespace Data {
    public class ThamSoRepository {
        /// <summary>
        /// lay ra quy dinh
        /// </summary>
        /// <param name="parameterName">tham so</param>
        /// <returns></returns>
        public int GetRules(string parameterName) {
            QuanLyNhaSachEntities context = new QuanLyNhaSachEntities();
            var query = (from item in context.ThamSoList
                        where item.TenThamSo == parameterName
                        select item.QuyDinh).FirstOrDefault();

            return Convert.ToInt32(query);
        }

        /// <summary>
        /// xem quy định này có được sử dụng hay ko?
        /// </summary>
        /// <param name="parameterName">tên tham số (dòng)</param>
        /// <returns>true / false</returns>
        public bool IsUsed(string parameterName) {
            QuanLyNhaSachEntities context = new QuanLyNhaSachEntities();
            var query = (from item in context.ThamSoList
                         where item.TenThamSo == parameterName
                         select item.SuDung).FirstOrDefault();
            if (Convert.ToInt32(query) == 0)
                return false;

            return true;
        }

        public List<ThamSoDTO> GetThamSoList() {
            List<ThamSoDTO> list = new List<ThamSoDTO>();
            QuanLyNhaSachEntities context = new QuanLyNhaSachEntities();
            var query = from tsItem in context.ThamSoList
                        select tsItem;
            foreach(THAMSO item in query){
                ThamSoDTO dto = new ThamSoDTO();
                Mapper.CreateMap<THAMSO, ThamSoDTO>();
                dto = Mapper.Map<THAMSO, ThamSoDTO>(item);

                list.Add(dto);
            }
            return list;
        }

        public bool UpdateThamSo(List<ThamSoDTO> thamSoList) {
            try {
                QuanLyNhaSachEntities context = new QuanLyNhaSachEntities();
                foreach (ThamSoDTO item in thamSoList) {
                    var query = (from tsItem in context.ThamSoList
                                 where tsItem.IDThamSo == item.IDThamSo
                                 select tsItem).First();
                    query.DienGiai = item.DienGiai;
                    query.QuyDinh = item.QuyDinh;                    
                }
                
                context.SaveChanges();
                return true;
            }
            catch {
                return false;
            }
        }
    }
}
